#!/bin/bash
#

if [ $# = 0 ]
then
echo "mhd2vpx script"
echo
echo "Convert a .mhd image to a .vpx image"
echo
echo "Usage:"
echo 
echo "mhd2vpx <image.mhd>"
echo
echo "The result is saved as image.vpx and image.vhd"
echo
echo "The voxelspacing is not written, because it's not stored in the vpx."
echo "However, it is stored in a .vhd, which is not used in iX, but Koen"
echo "uses it. You can make a .vhd with the following command:"
echo
echo "chunk im.vpx im.vpx"
echo "which generates im.vhd"
echo
echo "then with the command:"
echo "add_pixelinfo pixelsize slicethickness im"
echo "the pixelsize and slicethickness are written to im.vhd."
echo
echo "So, in fact, this script could be extended by letting it search"
echo "for the .vhd and try to write the pixelspacings."
echo
echo "NB: Currently only supports (unsigned) char, (unsigned) short, (unsigned) long, float, and double."
echo "NB: Vector images are currently not supported, allthough dido has the option to create rgb8, rgb16, complexfloat, and complexdouble types."
exit 64
fi


mhdimages=`ls $*`
for mhdimage in $mhdimages
do
	echo "mhd-image to convert: $mhdimage"

	# Get the raw name and vpx name
	namesize=${#mhdimage[0]}
	ext=${mhdimage:$namesize-3:3}
	base=${mhdimage:0:$namesize-3}
	rawimage=$base"raw"
	vpximage=$base"vpx"

	# check if ext == mhd
	if [ "$ext" != "mhd" ]
	then
		echo "ERROR: The extension is not \"mhd\""
		exit
	fi

	# Get the image dimension
	dim=`less $mhdimage | grep NDims`
	dim=${dim/NDims = }

	# Get the image size
	size=`less $mhdimage | grep DimSize`
	size=${size/DimSize = }

	# Get the pixel type
	ptype=`less $mhdimage | grep ElementType`
	ptype=${ptype/ElementType = }
	# Translate it to vpx language
	outputtype="unknown"
	if [ "$ptype" = "MET_CHAR" ]
	then
		outputtype="bit8"
	fi
	if [ "$ptype" = "MET_UCHAR" ]
	then
		outputtype="ubit8"
	fi
	if [ "$ptype" = "MET_SHORT" ]
	then
		outputtype="bit16"
	fi
	if [ "$ptype" = "MET_USHORT" ]
	then
		outputtype="ubit16"
	fi
	if [ "$ptype" = "MET_INT" ]
	then
		outputtype="bit32"
	fi
	if [ "$ptype" = "MET_UINT" ]
	then
		outputtype="ubit32"
	fi
	if [ "$ptype" = "MET_LONG" ]
	then
		outputtype="bit32"
	fi
	if [ "$ptype" = "MET_ULONG" ]
	then
		outputtype="ubit32"
	fi
	if [ "$ptype" = "MET_FLOAT" ]
	then
		outputtype="float"
	fi
	if [ "$ptype" = "MET_DOUBLE" ]
	then
		outputtype="double"
	fi

	if [ "$ptype" = "unknown" ]
	then
		echo "$mhdimage has unsupported pixel type: $ptype"
		exit
	fi

	# Do the actual conversion
	echo "Converting .mhd to .vpx ..."
	dido -input raw -$outputtype -$dim"d" $size $rawimage $vpximage
	echo "Done!"

done #for mhdimage in $mhdimages


# Exit script
exit

